<template>
  <div>

      <!-- 新增生活按钮 -->
      <el-button type="primary" @click="showAddDialog">新增生活</el-button>


    <!-- 生活列表 -->
    <el-table :data="competitions" style="width: 100%">
      <!-- 生活列 -->
      <el-table-column prop="title" label="标题"  />
      <el-table-column prop="organizer" label="主办方"  />
      <el-table-column prop="category" label="类别" />
      <el-table-column prop="employeeNumber" label="添加人工号" />

      <!-- 图片列 -->
      <el-table-column label="图片">
        <template v-slot="scope">
          <img
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              width="100"
              height="100"
              alt="生活封面"
          />
          <span v-else>无图片</span>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="250">
        <template v-slot="scope">
          <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" @click="deleteCompetition(scope.row.id)">删除</el-button>
          <el-button type="info" @click="showDetailDialog(scope.row.content)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 编辑生活对话框 -->
    <Dialog :show="editDialogInfo.show"
            :title="editDialogInfo.title"
            :buttons="editDialogInfo.buttons"
            :width="'50%'"
            @close="editDialogInfo.show = false">
      <el-form ref="editFormRef"
               :model="formData"
               :rules="rules"
               label-width="110px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="标题"
                          prop="title">
              <el-input :maxLength="30"
                        v-model="formData.title" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主办方"
                          prop="organizer">
              <el-input :maxLength="100"
                        v-model="formData.organizer" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="类别"
                          prop="category">
              <el-input v-model="formData.category" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="添加人工号"
                          prop="employeeNumber">
              <el-input v-model="formData.employeeNumber" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="图片"
                          prop="photoUrl">
              <el-upload
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :show-file-list="false">
                <el-button type="primary">上传图片</el-button>
              </el-upload>
              <!-- <img v-if="formData.photoUrl"
                   :src="formData.photoUrl"
                   width="100"
                   height="100"
                   alt="生活图片" /> -->
                   <!-- 显示当前图片 -->
                   <img :src="imageUrl" width="200" height="200" alt="生活图片" v-if="imageUrl" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
  <el-col :span="24">
    <el-form-item label="详情" prop="content">
      <editor-html
        id="content"
        ref="content"
        :height="300"
        v-model="formData.content"
        :custom-upload="customUploadImage"
        :read-only="false"
      />
    </el-form-item>
  </el-col>
</el-row>
      </el-form>
    </Dialog>

    <!-- 详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="详情"
        width="50%">
      <div v-html="detailContent"></div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus';
import Dialog from '@/components/MyDialog.vue';
import EditorHtml from '@/components/EditorHtml.vue';

// 生活数据
const competitions = ref([]);

// 编辑对话框信息
const editDialogInfo = reactive({
    show: false,
    title: '',
    buttons: [
        {
            type: 'primary',
            text: '确定',
            click: () => saveCompetition()
        }
    ]
});

// 表单数据
const formData = reactive({
    title: '',
    organizer: '',
    category: '生活',
    employeeNumber: localStorage.getItem('employeeNumber') || '',
    photoUrl: '',
    content: ''
});

// 详情对话框
const detailDialogVisible = ref(false);
const detailContent = ref('');

// 表单验证规则
const rules = {
    title: [{ required: true, message: '标题不能为空' }],
    organizer: [{ required: true, message: '主办方不能为空' }],
    category: [{ required: true, message: '类别不能为空' }],
    employeeNumber: [{ required: true, message: '添加人工号不能为空' }],
    content: [{ required: true, message: '详情不能为空' }]
};

// 组件是否已挂载
const isMounted = ref(true);

// 获取生活数据
const fetchCompetitions = async () => {
    try {
        const response = await service.get('/admin/life/listAll');
        const data = response.data;

        // 遍历竞赛数据，加载图片
        for (const competition of data) {
            if (competition.photoUrl) {
                competition.imageUrl = await loadImage1(competition.photoUrl);
                console.log('加载图片成功:', competition.imageUrl);
            } else {
                competition.imageUrl = '';
            }
        }

        competitions.value = data;
    } catch (error) {
        console.error('获取生活数据失败', error);
    }
};

// 显示新增对话框
const showAddDialog = () => {
    editDialogInfo.title = '新增生活';
    Object.assign(formData, {
        title: '',
        organizer: '',
        category: '生活',
        employeeNumber: localStorage.getItem('employeeNumber') || '',
        photoUrl: '',
        content: ''
    });
    imageUrl.value = ''; // 清空图片 URL
    editDialogInfo.show = true;
};

// 显示编辑对话框
const showEditDialog = (competition) => {
    editDialogInfo.title = '编辑生活';
    imageUrl.value = ''; // 清空图片 URL
    Object.assign(formData, { ...competition });
    if (competition.photoUrl) {
        loadImage(competition.photoUrl); // 加载新图片
    }
    editDialogInfo.show = true;
};

// 显示详情对话框
const showDetailDialog = (content) => {
    detailContent.value = content;
    detailDialogVisible.value = true;
};

// 保存生活信息（新增或更新）
const saveCompetition = async () => {
    try {
        const url = formData.id ? '/admin/life/update' : '/admin/life/save';
        const method = formData.id ? 'put' : 'post';
        const response = await service[method](url, formData);

        if (response) {
            await fetchCompetitions();
            editDialogInfo.show = false;
            ElMessage.success('生活信息保存成功');
        } else {
            ElMessage.error(response.message || '生活信息保存失败');
        }
    } catch (error) {
        console.error('保存生活信息失败', error);
        ElMessage.error('生活信息保存失败');
    }
};

// 删除生活
const deleteCompetition = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该生活吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await service.delete(`/admin/life/${id}`);
        await fetchCompetitions();
        ElMessage.success('生活删除成功');
    } catch (error) {
        console.error('删除生活失败', error);
        ElMessage.error('生活删除失败');
    }
};

const customUploadImage = async (file, insertImage) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await service.post('/upload/image', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });

        // 假设后端返回的图片 URL 在 response.data 中
        const imageUrl = response.data;

        // 插入图片到编辑器
        insertImage(imageUrl);

        // 更新表单中的图片 URL
        formData.photoUrl = imageUrl;

        ElMessage.success('图片上传成功');
    } catch (error) {
        console.error('图片上传失败', error);
        ElMessage.error('图片上传失败，请重试');
    }
};

// 临时图片URL
const imageUrl = ref('');

// 图片上传前的处理
const handleBeforeUpload = (file) => {
    const formData = new FormData();
    formData.append('file', file);

    service.post('/upload/image', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
        .then(response => {
            handleUploadSuccess(response.data);
            console.log('图片上传成功，路径为:', response.data);
        })
        .catch(error => {
            handleUploadError(error);
        });

    return false; // 阻止默认上传行为
};

// 图片上传成功
const handleUploadSuccess = (response) => {
    if (response) {
        formData.photoUrl = response; // 更新表单中的图片路径
        imageUrl.value = response; // 更新图片 URL
        loadImage(response); // 加载新图片
        console.log('图片上传成功，路径为:', response);
        ElMessage.success('图片上传成功');
    }
};

// 图片上传失败
const handleUploadError = (error) => {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败，请重试');
};

// 加载图片
const loadImage = (imagePath) => {
    console.log('加载图片:', imagePath);
    imageUrl.value = ''; // 清空图片 URL

    service.get(`/images/${imagePath}`, {
        responseType: 'blob'
    })
        .then(response => {
            imageUrl.value = URL.createObjectURL(response.data); // 更新图片 URL
            console.log('加载图片 URL:', imageUrl.value);
        })
        .catch(error => {
            console.error('图片加载失败', error);
            ElMessage.error('图片加载失败，请重试');
        });
};

// 异步加载图片
const loadImage1 = async (imagePath) => {
    console.log('加载图片:', imagePath);

    try {
        const response = await service.get(`/images/${imagePath}`, {
            responseType: 'blob'
        });
        const imageUrl = URL.createObjectURL(response.data);
        console.log('加载图片成功，URL:', imageUrl);
        return imageUrl;
    } catch (error) {
        console.error('图片加载失败', error);
        ElMessage.error('图片加载失败，请重试');
        return '';
    }
};

// 组件挂载时获取生活数据
onMounted(() => {
    fetchCompetitions();
});

// 组件卸载时标记为未挂载
onUnmounted(() => {
    isMounted.value = false;
});
</script>